#pragma once
#include <queue>
#include <iostream>
#include <string>
#include <vector> //用vector管理线程
#include <memory>
#include "log.hpp"
#include "Thread.hpp"
#include "Mutex.hpp"
#include "Cond.hpp"

namespace ThreadPoolModule
{
    using namespace LockModule;
    using namespace ThreadModule;
    using namespace CondModule;
    using namespace LogModule;

    const static int defaultnum = 5;
    using thread_t = std::shared_ptr<Thread>;

    void Defaulttest()
    {
        while (true)
        {
            LOG(LogLevel::INFO) << "test";
            sleep(1);
        }
    }

    template <typename T>
    class ThreadPool
    {
    private:
        bool IsEmpty()
        {
            return _taskq.empty();
        }

        // 执行任务
        void HandlerTask(std::string name)
        {
            LOG(LogLevel::INFO)<<"线程"<< name <<"进入handlerTask";
            // 线程醒来就一直执行
            while (true)
            {
                T t;
                {
                    LockGuard lockguard(_mutex);
                    while (IsEmpty() && _isrunning)
                    {
                        _wait_num++;
                        _cond.Wait(_mutex);
                        _wait_num--;
                    }
                    // 任务队列为空 && 线程池退出了才退出    ,重要重要 
                    if(IsEmpty() && !_isrunning)
                        break;


                    // 1.拿任务
                     t = _taskq.front();
                    _taskq.pop();
                }

                //在临界区外 ,处理任务 ,效率更高
                // 2.处理任务   规定传入的所有的任务, 必须提供()方法
                t();
            }
            LOG(LogLevel::INFO) << "线程: " << name << " 退出";
        }
        ThreadPool(const ThreadPool<T> &) = delete;//拷贝构造禁掉
        ThreadPool<T>& operator=(const ThreadPool<T> &) = delete;//赋值重载禁掉

        ThreadPool(int num = defaultnum) //构造函数设为私有
            : _num(num)
            ,_wait_num(0)
            ,_isrunning(false)
        {
            // 创建num个线程
            for (int i = 0; i < num; i++)
            {
                //bind  此时所有创建出来的线程,转而去执行HandlerTask
                _threads.push_back(std::make_shared<Thread>(std::bind(&ThreadPool::HandlerTask, this,std::placeholders::_1 )));
                LOG(LogLevel::INFO) << "构建线程" << _threads.back()->Name() << "成功";
            }
        }

    public:

        static ThreadPool<T> * getInstance() //单例模式
        {
	        if(_instance == NULL)
            {
	            LockGuard lockguard(_mutex_singleton);
                if(_instance == NULL)
                {
                    LOG(LogLevel::INFO) << "单例首次被执行，需要加载对象...";
                    _instance = new ThreadPool<T>();
                    _instance->Start();
                }
	        }

            return _instance;
        }
        
        ~ThreadPool()
        {
        }

        void Start()
        {
            if(_isrunning) return;
            _isrunning = true; // bug fix??

            for (auto &thread_ptr : _threads)
            {
                thread_ptr->Start();
                LOG(LogLevel::INFO) << "启动线程" << thread_ptr->Name() << "成功";
            }
        }

        void Wait()
        {
            for (auto &thread_ptr : _threads)
            {
                thread_ptr->Join();
                LOG(LogLevel::INFO) << "回收线程" << thread_ptr->Name() << "成功";

            }
        }

        //任务入队列
        void Enqueue(T in)//这个会被多线程调用 ,先加锁
        {   
            //只要队列扛得住 ,就一直加
            LockGuard lockguard(_mutex);
            if(!_isrunning) return;
            _taskq.push(in);
            if(_wait_num > 0 ) 
                _cond.Notify();

        }

        //退出线程池
        void Stop()
        {
            LockGuard lockguard(_mutex);
            if(_isrunning)
            {
                // 3. 不能在入任务了
                _isrunning = false; // 不工作
                // 1. 让线程自己退出(要唤醒) && // 2. 历史的任务被处理完了
                if(_wait_num>0)
                    _cond.NotifyAll();
            }
        }

    private:
        int _num;                       // 线程个数
        std::queue<T> _taskq;           // 任务队列  是临界资源
        std::vector<thread_t> _threads; // 管理线程 ,其中是线程的指针

        Mutex _mutex;
        Cond _cond;
        int _wait_num;

        bool _isrunning ;               //线程池的运行状态

        static ThreadPool<T>* _instance; //单例模式的静态指针
        static Mutex _mutex_singleton;//只用来保护单例
    };

    //静态方法初始化应放在类外
    template<typename T>
    ThreadPool<T> *ThreadPool<T>::_instance = NULL;
    template<typename T>
    Mutex ThreadPool<T>::_mutex_singleton; //只用来保护单例
}